package com.jfinal.demo.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.demo.model.Blog;
import com.jfinal.demo.model.User;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.sql.SQLException;
import java.util.List;

/**
 * Title:
 * Description:
 *
 * @version 2.0
 * @author: Yung Fu(FUYUNGCN AT GMAIL DOT com)
 * @since: 14-9-21 上午11:32
 */
public class AdminController extends Controller {

    /**
     * 事务处理
     */
    public void transactionTest() {
        final int id1 = Integer.parseInt(getPara(0));
        final int id2 = Integer.parseInt(getPara(1));
        boolean flag = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                int count1 = Db.update("update user set name = ? where id = ?", "张三", id1);

                int count2 = Db.update("update user set name = ? where id = ?", "李四", id2);
                System.out.println("count1: " + count1 + " count2: " + count2);
                return count1 == 1 && count2 == 1;
            }
        });
        if (flag)
            renderText("更新成功，提交事务...");
        else
            renderText("更新失败，回滚事务...");
    }

    /**
     * 声明式事务（ActiveRecord支持）
     *
     * 出现异常时进行回滚
     */
    @Before(Tx.class)
    public void transactionTest2() {
        int id1 = Integer.parseInt(getPara(0));
        int id2 = Integer.parseInt(getPara(1));

        User.dao.findById(id1).set("name", "张三").update();

        User.dao.findById(id2).set("name", "李四").update();

        renderText("提交事务");
    }

    public void updateUser() {
        int id1 = Integer.parseInt(getPara(0));
        int id2 = Integer.parseInt(getPara(1));

        User.dao.findById(id1).set("name", "张三").update();

        User.dao.findById(id2).set("name", "李四").update();

        renderText("提交事务");
    }

    public void userupdate() {
        int id1 = Integer.parseInt(getPara(0));
        int id2 = Integer.parseInt(getPara(1));

        User.dao.findById(id1).set("name", "张三").update();

        User.dao.findById(id2).set("name", "李四").update();

        renderText("提交事务");
    }

    /**
     * user与blog关联查询
     */
    public void relation() {
        int id = Integer.parseInt(getPara(0));
        String sql = "select b.*,u.* from user u left join blog b on u.id = b.user_id where u.id=?";
//        Blog blog = Blog.dao.findFirst(sql, id);
//        renderText("title：" + blog.get("title").toString());

        List<Blog> blogs = Blog.dao.find (sql, id);
        for (Blog blog : blogs) {
            System.out.println("name:" + blog.getUserById().get("name"));
        }
    }
}
